using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Rensoft.CRM.Client.AccountsAPI;
using Rensoft.CRM.Client.Editors;

namespace Rensoft.CRM.Client.ItemViews
{
    public partial class InvoiceView : Rensoft.CRM.Client.ItemViews.BaseView
    {
        private List<Invoice> invoiceList;

        public Invoice[] InvoiceArray
        {
            get { return invoiceList.ToArray(); }
            set { invoiceList = new List<Invoice>(value); }
        }

        public InvoiceView()
        {
            InitializeComponent();
        }

        public InvoiceView(Program program)
            : base(program)
        {
            InitializeComponent();
        }

        protected override void LoadComplete(RunWorkerCompletedEventArgs e)
        {
            base.LoadComplete(e);

            if (invoiceList != null)
            {
                invoiceList.Sort(new Comparison<Invoice>(invoiceSorter));

                ItemsListView.VirtualListSize = invoiceList.Count;
                ItemsListView.VirtualMode = true;
                UpdateItemCount(invoiceList.Count);
            }
            else
            {
                // No items downloaded, so count is 0.
                UpdateItemCount(0);
            }
        }

        private int invoiceSorter(Invoice left, Invoice right)
        {
            int leftNumber = int.Parse(left.InvoiceRef);
            int rightNumber = int.Parse(right.InvoiceRef);

            if (leftNumber > rightNumber)
            {
                return (ItemsListView.Sorting == SortOrder.Descending) ? -1 : 1;
            }
            else if (leftNumber < rightNumber)
            {
                return (ItemsListView.Sorting == SortOrder.Descending) ? 1 : -1;
            }

            return 0;
        }

        protected override void OnRetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
        {
            Invoice invoice = InvoiceArray[e.ItemIndex];

            e.Item = new ListViewItem(
                new string[] {
                    invoice.AccountCode,
                    invoice.ValueAmount.ToString("N"),
                    invoice.InvoiceRef,
                    invoice.Date.ToShortDateString()
                });

            e.Item.Tag = invoice;

            base.OnRetrieveVirtualItem(sender, e);
        }

        internal override BaseEditor GetEditor()
        {
            throw new NotImplementedException();
        }

        private void ItemsListView_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == Keys.Enter) && (ItemsListView.SelectedIndices.Count == 1))
            {
                PerformEditorOpen(ItemsListView.FocusedItem.Tag);
            }
        }
    }
}